package com.company.thread;

/**
 * @description: some desc
 * @author: ruoan
 * @date: 2020/10/24 16:13
 */
public class Thread18 {


    public static void main(String[] args) throws InterruptedException {


        TwoPhaseTermination twoPhaseTermination = new TwoPhaseTermination();
        twoPhaseTermination.start();
        Thread.sleep(5000);
        twoPhaseTermination.stop();


    }
}

/**
 * 两阶段终止设计模式
 */
class TwoPhaseTermination {
    private Thread monitor;

    // 开始线程
    public void start(){
        // 绑定线程任务
        Runnable r = new Runnable() {
            @Override
            public void run() {
                while (true) {
                    boolean interrupted = Thread.currentThread().isInterrupted();
                    work();  // 正常业务
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        interrupted = true;//  如果阻塞的时候被设置打断标记，会被catch到，此时会把标记又重设置为false,这样就不能退出了
                        e.printStackTrace();
                    }
                    if (interrupted) {
                        // 如果监测到外部打断,就自行了断
                        work();// 善后
                        return;
                    }

                }
            }
        };
        monitor = new Thread(r,"monitor thread");
        monitor.start();
    }
    // 线程做的事情
    private void work(){
        System.out.println("I am working...");
    }

    // 关闭线程
    public void stop(){

        if (monitor != null) {
            monitor.interrupt();
        }else{
            throw new RuntimeException("监视线程未初始化");
        }
    }

}
